import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/model_info.dart';

class SettingsScreen extends StatefulWidget {
  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  String _selectedModelId = '';
  final TextEditingController _apiKeyController = TextEditingController();
  final _prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    final prefs = await _prefs;
    setState(() {
      _selectedModelId = prefs.getString('selected_model') ?? ModelConfig.models[0].id;
      _apiKeyController.text = prefs.getString('api_key') ?? '';
    });
  }

  Future<void> _saveSettings() async {
    final prefs = await _prefs;
    await prefs.setString('selected_model', _selectedModelId);
    await prefs.setString('api_key', _apiKeyController.text);
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('设置已保存')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设置'),
        actions: [
          IconButton(
            icon: Icon(Icons.save),
            onPressed: _saveSettings,
          ),
        ],
      ),
      body: ListView(
        padding: EdgeInsets.all(16),
        children: [
          Text(
            '选择模型',
            style: Theme.of(context).textTheme.titleLarge,
          ),
          SizedBox(height: 8),
          ...ModelConfig.models.map((model) => RadioListTile(
            title: Text(model.name),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(model.description),
                Text(
                  model.pricing,
                  style: TextStyle(
                    color: model.pricing == '免费' ? Colors.green : Colors.orange,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            value: model.id,
            groupValue: _selectedModelId,
            onChanged: (value) {
              setState(() {
                _selectedModelId = value.toString();
              });
            },
          )).toList(),
          SizedBox(height: 24),
          Text(
            'API Key 设置',
            style: Theme.of(context).textTheme.titleLarge,
          ),
          SizedBox(height: 8),
          TextField(
            controller: _apiKeyController,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'API Key',
              hintText: '请输入您的 API Key',
            ),
            obscureText: true,
          ),
        ],
      ),
    );
  }
} 